<?php namespace App\Controllers;

use \App\App;

class Book extends App
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index($param)
    {
        $params = explode("/", $param);
        $id     = $params[0];
        if (isset($params[1]) && $params[1] == "cloud") {
            $this->readCloud($id);
        } else {
            $this->readLocal($id);
        }
    }

    public function readCloud($id)
    {
        $api     = new \App\Models\Api(1);
        $source  = $api->getUrl("source", ["view" => "summary", "book" => $id]);
        $cloudid = "";
        foreach ($source as $s) {
            if ($s['source'] == $this->setting->getSetting('apiSource')) {
                $cloudid = $s['_id'];
            }
        }
        $cloudid = $cloudid ?: (count($source) > 1 ? $source[1]['_id'] : $source[0]['_id']);

        $story          = $api->getUrl("info", ['sp' => $id]);
        $story['id']    = $this->crypt->md5($story['title'] . $story['author']);
        $story['cloud'] = $cloudid;
        $this->saveCloud($story);
        $this->readLocal($story['id']);
    }

    public function readLocal($id)
    {
        $storyModel = new \App\Models\Story();
        $story      = $storyModel->find($id);
        if (!$story) {
            showError("没有找到小说");
        }
        if ($story['type'] == "cloud") {
            $sql   = " show tables like '{$id}' ";
            $table = $this->db->query($sql)->first();
            if (!$table) {
                $storyModel->createDB($story);
            }
        }
        $story['click'] += 1;
        $storyModel->update(['click' => $story['click']], ['id' => $story['id']]);
        $favo                    = new \App\Models\Favorites();
        $this->view->story       = $story;
        $this->view->category    = $this->db->table("category")->where('name', $story['category'])->get()->first();
        $this->view->subcategory = $this->db->table("category")->where('name', $story['sub_category'])->get()->first();
        $this->view->favorites   = $this->user ? $favo->check($this->user['id'], $id) : false;
        $this->view->comments    = $this->comment($id);
        $this->view->viewTitle   = $story['title'];
        $this->render("/front/book/info", "/front/header");
    }

    public function comment($storyID)
    {
        $commentModel = new \App\Models\Comment();
        return $commentModel->select("comment.*,users.username,users.avatar")
            ->join("users", "users.id=comment.user")
            ->limit(20, 0)
            ->order("date", "DESC")
            ->get(['story' => $storyID]);
    }

    public function chapters($storyID, $order = 0)
    {
        $storyModel = new \App\Models\Story();
        $story      = $storyModel->find($storyID);
        if ($story['type'] == 'cloud') {
            $this->downChapter($storyID);
        }

        $chapters             = $storyModel->chapters($storyID, $order == 0 ? "ASC" : "DESC");
        $this->view->storyid  = $storyID;
        $this->view->chapters = $chapters;
        $this->render("/front/book/chapters", "/front/header");
    }

    public function downChapter($storyID)
    {
        $storyModel = new \App\Models\Story();
        $story      = $storyModel->find($storyID);
        $storyModel->cloudChapterList($story, true);
    }

    private function saveCloud($story)
    {
        $api = new \App\Models\Api(1);
        //下载封面图片到本地服务器
        $image      = new \System\Image();
        $storyModel = new \App\Models\Story();
        $imageUrl   = $api->getUrl("static", "", false) . $story['cover'];

        $story['cover'] = $image->download($imageUrl, $story['id'], BASE_PATH . "/assets/images/covers");
        $book           = $storyModel->find($story['id']);
        if (!$book) {
            $book = [
                "id"           => $story['id'],
                "title"        => $story['title'],
                "author"       => $story['author'],
                "desc"         => $story['longIntro'],
                "category"     => $story['majorCate'],
                "sub_category" => $story['minorCate'],
                "time"         => time(),
                "click"        => 0,
                "cover"        => $story['cover'],
                "cloud"        => $story['cloud'],
                "type"         => "cloud",
                "approve"      => 1,
            ];
            $storyModel->save($book);
        }
        return $book;
    }

    public function read($storyID, $chapterID)
    {
        $storyModel            = new \App\Models\Story();
        $this->view->story     = $storyModel->find($storyID);
        $chapter               = $storyModel->chapter($storyID, $chapterID);
        $this->view->chapters  = $storyModel->chapters($storyID);
        $this->view->chapter   = $chapter;
        $this->view->viewTitle = $chapter['title'];
        $this->render("/front/book/read", "", true);
    }
}